home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_03 / kamradt / pcount.h < prev    next >
C/C++ Source or Header  |  1994-02-07  |  801b  |  48 lines

  1. class String {
  2. private:
  3.   struct StringImp {
  4.     char *ptr;  
  5.     unsigned count;
  6.     StringImp(const char *str) 
  7.       : ptr(strdup(str)), 
  8.         count(1) 
  9.     { 
  10.       ; 
  11.     }
  12.     ~StringImp() 
  13.     { 
  14.       delete[] ptr; 
  15.     }
  16.   } *imp;
  17. public:
  18.   String(const char *str) 
  19.   { 
  20.     imp = new StringImp(str); 
  21.   }
  22.   String(const String &str) 
  23.   { 
  24.     imp = str.imp; 
  25.     imp->count++; 
  26.   }
  27. // assignment is a little tricky
  28.   String &
  29.   operator=(const String &str) 
  30.   {
  31. // increment first in case 
  32. // of assignment to self
  33.     str.imp->count++;  
  34. // be sure to clean up the old imp!
  35.     if(--imp->count == 0) 
  36.       delete imp;       
  37.     imp = str.imp;
  38.     return *this;
  39.   }
  40.   ~String() 
  41.   { 
  42.     if(--imp->count == 0) 
  43.       delete imp; 
  44.   }
  45. };
  46.  
  47.  
  48.